new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Table_Name: '',//表名
                isChildrenTable: false,//是否为子表
                Parent_Table_Name: '',
                Parent_Primary_Key: '',
                Foreign_Key: '',
                index: '',
                Children: {
                    base_table_detail: [{
                        Table_Detail_Name: '',//名称
                        Table_Detail_Label: '',//备注
                        Table_Detail_Type: 'varchar',//类型
                        Table_Detail_Length: 50,//长度
                        Table_Detail_Default: '',//默认值
                        Table_Detail_Index: '',//索引
                        isNull: false,
                        isPrimaryKey: true,
                        isRemove: false
                    }],
                }
            },
            Table: [],//所有表名
            Column: [],//字段
            rules: {
                Table_Name: [{ required: true, message: '请输入表名称', trigger: 'blur' }],
                Table_Detail_Name: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
                Foreign_Key: [{ required: true, message: '请选择被栏位', trigger: 'change' }],
                Parent_Table_Name: [{ required: true, message: '请选择被参考表', trigger: 'change' }],
                Parent_Primary_Key: [{ required: true, message: '请选择参考栏位', trigger: 'change' }],
                index: [{ required: true, message: '请输入名', trigger: 'blur' }],
            },
            Type: ['varchar', 'text'],
            loading: false,
        }
    },
    mounted() {
        const TABLE_NAME = sessionStorage.getItem("TABLE_NAME")
        this.getData(TABLE_NAME);
    },
    methods: {
        getData(Data) {
            const that = this
            $.ajax({//查询所有表
                headers:requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryAllTableName`,
                type: 'GET',
                success: function (data) {
                    if (data.length > 0) {
                        that.Table = data.filter(i => i.TABLE_NAME != Data)
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({//查询是否有外键
                headers:requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryForeignKeyByTableName`,
                type: 'GET',
                data: { Data },
                success: function (data) {
                    if (data.length == 1) {//默认只有1个外键
                        that.form.isChildrenTable = true;
                        that.form.isChildrenTable_Original = true;
                        that.form.Foreign_Key = data[0].COLUMN_NAME;
                        that.form.Foreign_Key_Original = data[0].COLUMN_NAME;
                        that.form.index = data[0].CONSTRAINT_NAME;
                        that.form.index_Original = data[0].CONSTRAINT_NAME;
                        that.form.Parent_Table_Name = data[0].REFERENCED_TABLE_NAME;
                        that.form.Parent_Table_Name_Original = data[0].REFERENCED_TABLE_NAME;
                        that.form.Parent_Primary_Key = data[0].REFERENCED_COLUMN_NAME;
                        that.form.Parent_Primary_Key_Original = data[0].REFERENCED_COLUMN_NAME;
                        console.log(that.form);
                        that.ChangeTable(data[0].REFERENCED_TABLE_NAME);
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({//查询字段并处理
                headers:requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryAllColumnByTableName`,
                type: 'GET',
                data: { Data },
                success: function (data) {
                    if (data.length > 0) {
                        console.log(data);
                        that.form.Table_Name = Data;
                        that.form.Table_Name_Original = Data;
                        that.form.Children.base_table_detail = []
                        data.forEach(item => {
                            let Table_Detail_Type = item.COLUMN_TYPE
                            let Table_Detail_Length = 0;
                            if (item.COLUMN_TYPE.includes('varchar')) {
                                Table_Detail_Type = item.COLUMN_TYPE.split('(')[0];
                                Table_Detail_Length = parseInt(item.COLUMN_TYPE.split('(')[1].replace(')', ''));
                            }
                            that.form.Children.base_table_detail.push({
                                Table_Detail_Name: item.COLUMN_NAME,//名称
                                Table_Detail_Name_Original: item.COLUMN_NAME,
                                Table_Detail_Label: item.COLUMN_COMMENT,//备注
                                Table_Detail_Label_Original: item.COLUMN_COMMENT,
                                Table_Detail_Type,//类型
                                Table_Detail_Type_Original: Table_Detail_Type,
                                Table_Detail_Length,//长度
                                Table_Detail_Length_Original: Table_Detail_Length,
                                Table_Detail_Default: item.COLUMN_DEFAULT && item.COLUMN_DEFAULT != 'NULL' ? item.COLUMN_DEFAULT : '',//默认值
                                Table_Detail_Default_Original: item.COLUMN_DEFAULT && item.COLUMN_DEFAULT != 'NULL' ? item.COLUMN_DEFAULT : '',
                                Table_Detail_Index: '',//索引
                                Table_Detail_Index_Original: '',
                                isNull: item.IS_NULLABLE != 'NO',
                                isNull_Original: item.IS_NULLABLE != 'NO',
                                isPrimaryKey: item.COLUMN_KEY == 'PRI',
                                isPrimaryKey_Original: item.COLUMN_KEY == 'PRI',
                                isRemove: false
                            })
                        })
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let obj = this.generateModifySQL(this.form)
                    if (obj.Status) {
                        that.loading = true;
                        if (obj.SQL) {
                            $.ajax({
                                headers:requestHeaders(),
                                url: `${BASE_URL2}/generalBusiness/generalDataTableOperation`,
                                type: 'POST',
                                data: {
                                    Data: obj.SQL
                                },
                                success: function (res) {
                                    console.log(res);
                                    if (res.Status === 'success') {
                                        that.$message.success("提交成功")
                                        window.location.href='./index.html'
                                    } else {
                                        that.$message.error("提交失败，请稍后再试")
                                    }
                                },
                                complete: function (XMLHttpRequest) {
                                    that.loading = false
                                    requestPretreatment(XMLHttpRequest);
                                },
                                dataType: "json"
                            })
                        }else{
                            window.history.go(-1)
                        }
                    } else {
                        this.$message({
                            message: '请选择主键！',
                            type: 'warning'
                        })
                        return false;
                    }
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        generateModifySQL(obj) {//生成sql
            //未删除的字段是否有主键
            if (obj.Children.base_table_detail.filter(item => !item.isRemove).some(item => item.isPrimaryKey && item.Table_Detail_Type == 'varchar')) {
                //表名
                let SQL = "";
                //被删除的字段
                obj.Children.base_table_detail.filter(item => item.isRemove).forEach(item => {
                    if (!SQL) {
                        SQL = "ALTER TABLE `" + obj.Table_Name + "`";
                        SQL = SQL + "\r\nDROP COLUMN `" + item.Table_Detail_Name_Original + "`";
                    } else {
                        SQL = SQL + ",\r\nDROP COLUMN `" + item.Table_Detail_Name_Original + "`";
                    }
                });
                //字段
                let base_table_detail = obj.Children.base_table_detail.filter(item => !item.isRemove);
                for (let i = 0; i < base_table_detail.length; i++) {
                    let item = base_table_detail[i];
                    //公共部分
                    let Table_Detail_Type = item.Table_Detail_Type;
                    let DEFAULT = "DEFAULT '" + item.Table_Detail_Default + "'";
                    //根据类型处理SQL
                    if (Table_Detail_Type == 'varchar') {
                        Table_Detail_Type = Table_Detail_Type + "(" + item.Table_Detail_Length + ")";
                    } else {
                        DEFAULT = "";
                    }
                    //判断当前字段是否有原值
                    if (Object.keys(item).some(item => item.includes('_Original'))) {
                        //原字段有变化
                        if (item.Table_Detail_Name != item.Table_Detail_Name_Original || item.Table_Detail_Label != item.Table_Detail_Label_Original
                            || item.Table_Detail_Type != item.Table_Detail_Type_Original || item.Table_Detail_Length != item.Table_Detail_Length_Original
                            || item.Table_Detail_Default != item.Table_Detail_Default_Original || item.Table_Detail_Index != item.Table_Detail_Index_Original
                            || item.isNull != item.isNull_Original) {

                            //表名是否变化
                            if (item.Table_Detail_Name != item.Table_Detail_Name_Original) {
                                if (!SQL) {
                                    SQL = "ALTER TABLE `" + obj.Table_Name + "`";
                                    SQL = SQL + "\r\nCHANGE COLUMN `" + item.Table_Detail_Name_Original + "` `" + item.Table_Detail_Name + "`  "
                                } else {
                                    SQL = SQL + ",\r\nCHANGE COLUMN `" + item.Table_Detail_Name_Original + "` `" + item.Table_Detail_Name + "`  "
                                }
                            } else {
                                if (!SQL) {
                                    SQL = "ALTER TABLE `" + obj.Table_Name + "`";
                                    SQL = SQL + "\r\nMODIFY COLUMN `" + item.Table_Detail_Name + "`  ";
                                } else {
                                    SQL = SQL + ",\r\nMODIFY COLUMN `" + item.Table_Detail_Name + "`  ";
                                }

                            }
                            //拼接"类型","允许为空","默认值"
                            SQL = SQL + Table_Detail_Type + " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci " + (item.isNull ? '' : ' NOT') + " NULL " + DEFAULT;
                            //拼接注释
                            if (item.Table_Detail_Label) {
                                SQL = SQL + " COMMENT '" + item.Table_Detail_Label + "'"
                            }
                            if (!base_table_detail[i - 1]) {//排序
                                SQL = SQL + " FIRST";

                            } else {
                                SQL = SQL + " AFTER `" + base_table_detail[i - 1].Table_Detail_Name + "`";
                            }
                        }
                    } else {//新增字段
                        if (!SQL) {
                            SQL = "ALTER TABLE `" + obj.Table_Name + "`";
                            SQL = SQL + "\r\nADD COLUMN `" + item.Table_Detail_Name + "`  " + Table_Detail_Type + (item.isNull ? '' : ' NOT') + " NULL " + DEFAULT + " COMMENT '" + item.Table_Detail_Label + "'";
                        } else {
                            SQL = SQL + ",\r\nADD COLUMN `" + item.Table_Detail_Name + "`  " + Table_Detail_Type + (item.isNull ? '' : ' NOT') + " NULL " + DEFAULT + " COMMENT '" + item.Table_Detail_Label + "'";
                        }
                        if (!base_table_detail[i - 1]) {//排序
                            SQL = SQL + " FIRST";

                        } else {
                            SQL = SQL + " AFTER `" + base_table_detail[i - 1].Table_Detail_Name + "`";
                        }
                    }
                }
                //判断主键是否有变化
                if (obj.Children.base_table_detail.some(item => item.isPrimaryKey != item.isPrimaryKey_Original)//新增或删除主键引起主键变化
                    || obj.Children.base_table_detail.some(item => item.isPrimaryKey && item.isRemove)) {//主键字段被删除，引起的主键变化
                    if (!SQL) {
                        SQL = "ALTER TABLE `" + obj.Table_Name + "`";
                        SQL = SQL + "\r\nDROP PRIMARY KEY";
                    } else {
                        SQL = SQL + ",\r\nDROP PRIMARY KEY";
                    }
                    //获取新增主键
                    if (base_table_detail.some(item => item.isPrimaryKey != item.isPrimaryKey_Original && item.isPrimaryKey)) {
                        SQL = SQL + ",\r\nADD PRIMARY KEY (";
                        base_table_detail.filter(item => item.isPrimaryKey).forEach((item, index) => {
                            if (index == 0) {
                                SQL = SQL + "`" + item.Table_Detail_Name + "`"
                            } else {
                                SQL = SQL + ", `" + item.Table_Detail_Name + "`"
                            }
                        })
                        SQL = SQL + ");\r\n"
                    } else {
                        SQL = SQL + ";\r\n"
                    }
                } else if (SQL) {
                    SQL = SQL + ";\r\n"
                }
                //判断是否新增外键
                if (obj.isChildrenTable != obj.isChildrenTable_Original || obj.Foreign_Key != obj.Foreign_Key_Original
                    || obj.index != obj.index_Original || obj.Parent_Table_Name != obj.Parent_Table_Name_Original
                    || obj.Parent_Primary_Key != obj.Parent_Primary_Key_Original) {
                    if (obj.isChildrenTable && !obj.isChildrenTable_Original) {//开始没有，新增外键
                        let endSQL = "ALTER TABLE `" + obj.Table_Name + "` ADD CONSTRAINT `" + obj.index + "` FOREIGN KEY (`" + obj.Foreign_Key + "`) REFERENCES `" + obj.Parent_Table_Name + "` (`" + obj.Parent_Primary_Key + "`);\r\n";
                        SQL = SQL + endSQL;
                    } else if (!obj.isChildrenTable && obj.isChildrenTable_Original) {//开始有外键，删除
                        let startSQL = "ALTER TABLE `" + obj.Table_Name + "` DROP FOREIGN KEY `" + obj.index_Original + "`;\r\n";
                        SQL = startSQL + SQL;
                    } else if (obj.isChildrenTable && obj.isChildrenTable_Original) {//开始有，修改
                        let startSQL = "ALTER TABLE `" + obj.Table_Name + "` DROP FOREIGN KEY `" + obj.index_Original + "`;\r\n";
                        let endSQL = "ALTER TABLE `" + obj.Table_Name + "` ADD CONSTRAINT `" + obj.index + "` FOREIGN KEY (`" + obj.Foreign_Key + "`) REFERENCES `" + obj.Parent_Table_Name + "` (`" + obj.Parent_Primary_Key + "`) ON DELETE RESTRICT ON UPDATE RESTRICT;\r\n";
                        SQL = startSQL + SQL + endSQL;
                    }
                }
                //修改表名
                if (obj.Table_Name_Original != obj.Table_Name) {
                    SQL = SQL + "RENAME TABLE " + obj.Table_Name_Original + " TO " + obj.Table_Name + ";\r\n";
                }
                return { Status: true, SQL }
            } else {
                //没有主键
                return { Status: false }
            }
        },
        base_table_detail_add() {//添加
            this.form.Children.base_table_detail.push({
                Table_Detail_Name: '',//名称
                Table_Detail_Label: '',//备注
                Table_Detail_Type: 'varchar',//类型
                Table_Detail_Length: 50,//长度
                Table_Detail_Default: '',//默认值
                isNull: false,
                Primary_Key: false,
                isRemove: false//true为被删除
            })
        },
        base_table_detail_remove() {//移除
            if (this.form.Children.base_table_detail.filter(item => !item.isRemove).length > 0) {
                let i = this.form.Children.base_table_detail.filter(item => !item.isRemove).length - 1
                let obj = this.form.Children.base_table_detail.filter(item => !item.isRemove)[i]
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    this.form.Children.base_table_detail.pop()
                } else {
                    this.$confirm('警告！此操作将删除一个字段,可能会影响系统运行, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this.form.Children.base_table_detail.filter(item => !item.isRemove)[i].isRemove = true;
                    }).catch(() => { });
                }
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        ChangeType(e, item) {//更新字段类型
            if (e == 'text') {
                item.Table_Detail_Length = 0;//长度默认0
                item.isPrimaryKey = false;//默认没有主键
                item.Table_Detail_Default = '';//默认没有默认值
                item.Table_Detail_Index = '';//默认没有索引
            } else if (e == 'varchar') {
                item.Table_Detail_Length = 50;//长度默认0
            }
        },
        ChangeTable(Data) {//选择表查询字段
            const that = this
            this.Column = [];//初始化
            $.ajax({
                headers:requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryAllColumnByTableName`,
                type: 'GET',
                data: { Data },
                success: function (data) {
                    console.log(data);
                    if (data.length > 0) {
                        that.Column = data;
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        }
    }
})